#include "mempool.h"

uint8_t MemBigPool[MEM_BIG_POOL_CNT*MEM_BIG_ITEM_SIZE];
uint8_t MemSmallPool[MEM_SMALL_POOL_CNT*MEM_SMALL_ITEM_SIZE];

uint8_t MemBigPoolMap[MEM_BIG_POOL_CNT >> 3];
uint8_t MemSmallPoolMap[MEM_SMALL_POOL_CNT >> 3];

void initMemPool(void)
{
    memset(MemBigPool, 0, sizeof(MemBigPool));
    memset(MemSmallPool, 0, sizeof(MemSmallPool));
    memset(MemBigPoolMap, 0, sizeof(MemBigPoolMap));
    memset(MemSmallPoolMap, 0, sizeof(MemSmallPoolMap));
}

int32_t getMemItem(MEM_POOL_TYPE_E type)
{
    uint8_t *ptr = 0;
    uint32_t cnt = 0;
    if(type == MEM_POOL_TYPE_SMALL) {
        ptr = MemSmallPoolMap;
        cnt = sizeof(MemSmallPoolMap);
    } else if(type == MEM_POOL_TYPE_SMALL) {
        ptr = MemBigPoolMap;
        cnt = sizeof(MemBigPoolMap);
    } else {
        return -1;
    }

    for(uint32_t i = 0;i < cnt;++i)
    {
        for(uint8_t j = 0;j < 8;++j)
            if(ptr[i] & (1 << j) == 0) {
                return (i << 3 + j);
            }

    }
    return -1;
}

void clearMemItem(MEM_POOL_TYPE_E type, uint32_t pos)
{
    if(type == MEM_POOL_TYPE_SMALL) {
        memset(MemSmallPool + pos * MEM_SMALL_ITEM_SIZE, 0, sizeof(MEM_SMALL_ITEM_SIZE));
        MemSmallPoolMap[pos >> 3] &= (~(1 << (pos % 8)));
    } else if(type == MEM_POOL_TYPE_SMALL) {
        memset(MemBigPool + pos * MEM_BIG_ITEM_SIZE, 0, sizeof(MEM_BIG_ITEM_SIZE));
        MemBigPoolMap[pos >> 3] &= (~(1 << (pos % 8)));
    }
}
